package com.ppxkk.city.app;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.ppxkk.city.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;
import java.security.MessageDigest;
import com.ppxkk.city.ui.base.BaseActivity;

public class LoginActivity extends Activity
{

    private Button 注册;
    private EditText 账号,密码;
    private HttpURLConnection h;
    private String 接口 = "http://i.agyer.com/user_info.json?type=info";
    private String key = "49ff2878167a5979";
    //后台Key值
    private String token = "1158e285f1cd9871b094fd1f056bb96f";

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        注册 = findViewById(R.id.mainButton1);
        账号 = findViewById(R.id.mainEditText1);
        密码 = findViewById(R.id.mainEditText2);
        注册.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View p1)
                {
                    String user=账号.getText().toString();
                    String pass=密码.getText().toString();
                    if (h != null)
                    {
                        h.disconnect();
                        h = null;
                    }
                    //MD5加密Token -> （key+user+pass+后台token值）
                    new Thread(new T(
                                   接口, 
                                   key, 
                                   user, 
                                   pass, 
                                   hash((key + user + pass + token).getBytes())
                               )).start();
                }
            });

    }

    private Handler hd=new Handler(){

        @Override
        public void handleMessage(Message msg)
        {

            super.handleMessage(msg);
            //获取更新来的内容
            Bundle data=msg.getData();
            String message;
            int result=0;
            String jsonString=data.getString("message", "{}");
            try
            {
                //解析js
                JSONObject js=new JSONObject(jsonString);
                result = js.getInt("code");
                //获取message的信息
                message = js.getString("message");
            }
            catch (JSONException e)
            {
                e.printStackTrace();
                message = "access error";
            }
            Toast.makeText(LoginActivity.this, message, Toast.LENGTH_LONG).show();
            if (result == 1)
            {
                String user=data.getString("user");
                if (user == null)
                {
                    return;
                }
                Intent i=new Intent();
                i.putExtra("user", user);
                i.putExtra("password",
                           data.getString("pass")
                           );
                setResult(-1, i);
                finish();
            }
        }

    };

    private class T implements Runnable
    {
        private String api;
        private String key;
        private String user;
        private String pass;
        private String token;

        public T(String api, String key, String user, String pass, String token)
        {
            this.api = api;
            this.key = key;
            this.user = user;
            this.pass = pass;
            this.token = token;
        }

        @Override
        public void run()
        {
            try
            {
                h = (HttpURLConnection) new URL(
                    api + "&key=" + key + "&token=" + token + "&user=" + user + "&pass=" + pass
                ).openConnection(Proxy.NO_PROXY);
                h.setRequestMethod("POST");
                /*h.addRequestProperty("key", this.key);
                 h.addRequestProperty("token", this.token);
                 h.addRequestProperty("user", this.user);
                 h.addRequestProperty("pass", this.pass);*/
                h.setUseCaches(true);
                h.setConnectTimeout(3000);
                h.connect();
                //读取流内容
                InputStream i=h.getInputStream();
                InputStreamReader ir=new InputStreamReader(i);
                BufferedReader br=new BufferedReader(ir);
                StringBuilder sb=new StringBuilder();
                String read;
                //循环读取
                while (true)
                {
                    read = br.readLine();
                    //没有了，跳出循环
                    if (read == null)
                    {
                        break;
                    }
                    sb.append(read);
                }
                h.disconnect();
                //通知更新
                Message m=new Message();
                Bundle bundle=new Bundle();
                bundle.putString("message",
                                 sb.toString()
                                 );
                bundle.putString("user", user);
                bundle.putString("pass", pass);
                m.setData(bundle);
                hd.sendMessage(m);
            }
            catch (Exception e)
            {
                e.printStackTrace();
                //通知更新
                Message m=new Message();
                Bundle bundle=new Bundle();
                bundle.putString("message", 
                                 e.getMessage()
                                 );
                m.setData(bundle);
                hd.sendMessage(m);
            }


        }
    }

    private String hash(byte[] btInput)
    {
        char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
        try
        {
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++)
            {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode != KeyEvent.KEYCODE_BACK)
        {
            return super.onKeyDown(keyCode, event);
        }
        if (h != null)
        {
            h.disconnect();
            h = null;
        }
        setResult(0);
        finish();
        return true;
    }




}

